package com.htd.erp.web;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

import com.htd.erp.common.LifeCycleUtils;
import com.htd.erp.common.Repository;
import com.htd.erp.model.AbstractEntity;

/**
 * @author Zhang Guilin
 *
 */
public abstract class AbstractEntityConverter<T extends AbstractEntity> implements Converter, Serializable {
	
	private static final long serialVersionUID = 5310095134693273140L;

	@Inject
	protected LifeCycleUtils lifeCycleUtils;
	
	@Inject
	private Repository genericRepository;
	
	protected List<T> list;
	
	abstract protected Class<T> getEntityClass();
	
	@PostConstruct
	public void postConstruct() {
		lifeCycleUtils.startConversation();
		list = buildSamples();
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String string) {
		if(string == null || getList() == null) {
			return null;
		}
		return find(string, getList());
	}
	
	@Override
	public String getAsString(FacesContext context, UIComponent component, Object object) {
		if(object == null || getList() == null) {
			return null;
		}
		@SuppressWarnings("unchecked")
		T t = (T) object;
		return t.getId().toString();
	}
	
	protected T find(String id, Collection<T> collection) {
		for(T t : collection) {
			if(StringUtils.equals(t.getId().toString(),id)) {
				return t;
			}
		}
		return null;
	}
	
	public List<T> getList() {
		return list;
	}
	
	protected Repository getRepository() {
		return genericRepository;
	}
	
	// override point
	protected List<T> buildSamples() {
		return getRepository().findAll(getEntityClass());
	}

}
